package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import com.hmdp.exception.ShopException;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Log
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Shop queryShopById(Long id) {
        //1.先去redis中查询
        String shopJson = redisTemplate.opsForValue().get(CACHE_SHOP_KEY+ id);
        //2.命中 直接返回
        if (shopJson != null) {
            log.info("命中缓存");
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //3未命中查询数据库
        Shop shop = getById(id);
        // 不纯在 返回错误
        if (shop == null) {
            throw new ShopException("商户不存在");
        }
        // 存在 放入到缓存中去，在返回
        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop));
        return shop;
    }
}
